//-------------------------------------------------------------------------------------
// <copyright file="DeployResource.cs" company="Achmea">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <summary>
//      Deploys an assembly into BizTalk.
// </summary>  
//-------------------------------------------------------------------------------------
namespace Microsoft.Sdc.Tasks.BizTalk2006.Assembly
{
    #region Using directives
    using System.Globalization;
    using System;
    using System.Collections.Generic;
    using BizTalk.ApplicationDeployment;
    using Microsoft.Build.Framework;
    #endregion

    /// <summary>
    /// Deploys an resource into BizTalk.
    /// </summary>
    /// <remarks>
    /// <code>
    /// <![CDATA[<BizTalk2006.Assembly.DeployResource 
    ///     Application="App" 
    ///     ResourceType="System.BizTalk:BizTalkAssembly" 
    ///     AssemblyPath="C:\Build\Output\MyAssembly.dll" 
    ///     Overwrite="True" 
    ///     Destination="C:\Output" 
    ///     Options="AddOnGac,AddOnMsi" 
    ///     Properties="TargetEnvironment='Development'" 
    ///     Server="." 
    ///     Database="BizTalkMgmtDb" 
    ///     Username="sa" 
    ///     Password="foo" />
    /// ]]>
    /// </code>
    /// <para>where:</para>
    /// <para><i>assemblyPath (Required)</i></para>
    /// <para>
    /// The path to the assembly. All neseccary information will be found to undeploy the artifact.
    /// </para>
    /// <para><i>ResourceType (Required)</i></para>
    /// <para>
    /// The ResourceType of the resource.
    /// <list type="string">
    ///     <item>System.BizTalk:Assembly</item>
    ///     <item>System.BizTalk:Bam</item>
    ///     <item>System.BizTalk:Bas</item> 
    ///     <item>System.BizTalk:BizTalkAssembly</item> 
    ///     <item>System.BizTalk:BizTalkBinding</item>
    ///     <item>System.BizTalk:Certificate</item>
    ///     <item>System.BizTalk:Com</item> 
    ///     <item>System.BizTalk:File</item> 
    ///     <item>System.BizTalk:PostProcessingScript</item> 
    ///     <item>System.BizTalk:PreProcessingScript</item> 
    ///     <item>System.BizTalk:Rules</item> 
    ///     <item>System.BizTalk:WebDirectory</item> 
    /// </list>
    /// <b>Be aware that deployment of Rules only succeed when the rule is already imported in the RulesEngine database
    /// It is better to use the BizTalk2004.Rules tasks to import, deploy, undeploy and delete rules.</b>
    /// </para>
    /// <para><i>Application</i></para>
    /// <para>
    /// The BizTalk application to where the resource should be deployed.
    /// </para>
    /// <para><i>Overwrite</i></para>
    /// <para>
    /// <b>true</b> to overwrite the resource when it is already deployed in BizTalk, or <b>false</b> otherwise. The default is <b>false</b>.
    /// </para>
    /// <para><i>Destination</i></para>
    /// <para>
    /// The destination of the resource when the files wille be copied from the MSI installer.
    /// </para>
    /// <para><i>Options</i></para>
    /// <para>
    /// Depending on the resourcetype some of the BizTalk resources can have options.
    /// Multiple options can be seperated with a ,
    /// <![CDATA[
    /// Options="GacOnAdd,GacOnInstall,GacOnImport,RegasmOnInstall,RegsvcsOnInstall,Regsvr32OnInstall"
    /// ]]>
    /// </para>
    /// <para><i>Properties</i></para>
    /// <para>
    /// Depending on the resourcetype some of the BizTalk resources can have properties.
    /// Properties a always described in the following structure: <![CDATA[PropertyName='PropertyValue']]>
    /// Multiple properties can be seperated with a ,
    /// </para>
    /// <para><i>Thumbprint</i></para>
    /// <para>
    /// The thumbprint value when a certificate is deployed. Only use when the ResourceType is Certificate
    /// </para>
    /// <para><i>Name</i></para>
    /// <para>
    /// The Name when a ruleset or BAS artifact is deployed. Only use when the ResourceType is BAS or Rules
    /// </para>
    /// <para><i>PolicyVersion</i></para>
    /// <para>
    /// The Version when a ruleset is deployed. Only use when the ResourceType is Rules
    /// <b>Be aware that deployment of Rules only succeed when the rule is already imported in the RulesEngine database
    /// It is better to use the BizTalk2004.Rules tasks to import, deploy, undeploy and delete rules.</b>
    /// </para>
    /// <para><i>SubType</i></para>
    /// <para>
    /// The SubType of the BAS artifact. Only use when the ResourceType is BAS
    /// </para>
    /// <para><i>SourceDocLibUrl</i></para>
    /// <para>
    /// The source url of the BAS template. Only use when the ResourceType is BAS
    /// </para>
    /// <para><i>server</i></para>
    /// <para>
    /// The logical name of the server hosting the BizTalk management database. If neither this nor the
    /// database name are specified then the installation will default to the local installation.
    /// </para>
    /// <para><i>database</i></para>
    /// <para>
    /// The name of the BizTalk management database. If neither this nor the server name are specified 
    /// then the installation will default to the local installation.
    /// </para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <BizTalk2006.Assembly.Addon.Deploy
    ///             Application="App"
    ///             ResourceType="System.BizTalk:BizTalkAssembly"
    ///             AssemblyPath="C:\Build\Output\MyAssembly.dll" 
    ///             Overwrite="True"
    ///             Destination="C:\Output"
    ///             Options="AddOnGac,AddOnMsi"
    ///             Properties="TargetEnvironment='Development'"
    ///             Server="." 
    ///             Database="BizTalkMgmtDb" 
    ///             Username="sa" 
    ///             Password="foo" />
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public class DeployResource : BizTalk2004.BizTalk2004TaskBase
    {
        #region Member Variables

        private string application;
        private bool overwrite;
        private string destination;
        private string assemblyPath;
        private string resourceType; // Should be an enumaration
        private string options;
        private string properties;
        private string thumbprint;
        private string name;
        private string version;
        private string subType;
        private string sourceDocLibUrl;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the application.
        /// </summary>
        /// <value>The application.</value>
        public string Application
        {
            get { return this.application; }
            set { this.application = value; }
        }

        /// <summary>
        /// Gets or sets the path to the assembly to deploy.
        /// </summary>
        /// <value>The path to the assembly to deploy.</value>
        [Required]
        public string AssemblyPath
        {
            get { return this.assemblyPath; }
            set { this.assemblyPath = value; }
        }

        /// <summary>
        /// Gets or sets the resourcetype
        /// </summary>
        /// <value>The resource type. 
        /// The following resource types can be filled
        /// <list type="string">
        ///     <item>System.BizTalk:Assembly</item>
        ///     <item>System.BizTalk:Bam</item>
        ///     <item>System.BizTalk:Bas</item> 
        ///     <item>System.BizTalk:BizTalkAssembly</item> 
        ///     <item>System.BizTalk:BizTalkBinding</item>
        ///     <item>System.BizTalk:Certificate</item>
        ///     <item>System.BizTalk:Com</item> 
        ///     <item>System.BizTalk:File</item> 
        ///     <item>System.BizTalk:PostProcessingScript</item> 
        ///     <item>System.BizTalk:PreProcessingScript</item> 
        ///     <item>System.BizTalk:Rules</item> 
        ///     <item>System.BizTalk:WebDirectory</item> 
        /// </list>
        /// </value>
        [Required]
        public string ResourceType
        {
            get { return this.resourceType; }
            set { this.resourceType = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Deploy"/> overwrites an existing assembly.
        /// </summary>
        /// <value><c>true</c> if overwrite; otherwise, <c>false</c>.</value>
        public bool Overwrite
        {
            get { return this.overwrite; }
            set { this.overwrite = value; }
        }

        /// <summary>
        /// Gets or Sets the destination value of the resource.
        /// </summary>
        /// <value>The destination folder</value>
        public string Destination
        {
            get { return this.destination; }
            set { this.destination = value; }
        }

        /// <summary>
        /// Gets or sets the options value of the resource
        /// You must separate multiple options with a comma
        /// </summary>
        /// <example>
        /// <code>
        /// <![CDATA[
        /// Options="GacOnAdd,GacOnInstall,GacOnImport,RegasmOnInstall,RegsvcsOnInstall,Regsvr32OnInstall"
        /// ]]>
        /// </code>
        /// </example>
        /// <value>The options value</value>
        public string Options
        {
            get { return this.options; }
            set { this.options = value; }
        }

        /// <summary>
        /// Gets or sets properties
        /// You must separate multiple properties with a comma
        /// </summary>
        /// <example>
        /// <code>
        /// <![CDATA[
        /// Property="TargetEnvironment=Deployment"
        /// ]]>
        /// </code>
        /// </example>
        /// <value>The properties</value>
        public string Properties
        {
            get { return this.properties; }
            set { this.properties = value; }
        }

        /// <summary>
        /// Gets or sets the thumbprint value when a certificate is deployed
        /// </summary>
        /// <value>The thumbprint.</value>
        public string Thumbprint
        {
            get { return this.thumbprint; }
            set { this.thumbprint = value; }
        }

        /// <summary>
        /// Gets or sets the Name when a ruleset or BAS artifact is deployed
        /// </summary>
        /// <value>The name of the policy or BAS artifact</value>
        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        /// <summary>
        /// Gets or sets the Version when a ruleset is deployed
        /// </summary>
        /// <value>The policyversion</value>
        public string Version
        {
            get { return this.version; }
            set { this.version = value; }
        }

        /// <summary>
        /// Gets or sets the SubType of the BAS artifact
        /// </summary>
        /// <value>The subtype</value>
        public string SubType
        {
            get { return this.subType; }
            set { this.subType = value; }
        }

        /// <summary>
        /// Gets or sets the source url of the BAS template
        /// </summary>
        /// <value>A url</value>
        public string SourceDocLibUrl
        {
            get { return this.sourceDocLibUrl; }
            set { this.sourceDocLibUrl = value; }
        }
        #endregion

        #region Methods

        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void InternalExecute()
        {
            BizTalk2004.Configuration.BizTalkInstallation installation = this.GetInstallation();

            string resourceType = this.ResourceType;
            resourceType = SdmParser.GetInstance().TransformResourceType(resourceType);

            using (Group group = new Group())
            {
                group.DBServer = installation.Server;
                group.DBName = installation.Database;

                try
                {
                    Application app = group.Applications[this.Application];
                    if (app != null)
                    {
                        app.UILevel = 2;
                        Dictionary<string, object> requestedProperties = new Dictionary<string,object>();
                        Dictionary<string, string> luidValues = new Dictionary<string, string>();

                        AddOptions(requestedProperties, this.Options);
                        AddProperties(requestedProperties, this.Properties);

                        // Check for the special options, each depending on which resource type is defined
                        if (!string.IsNullOrEmpty(this.Thumbprint))
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a property Thumbprint with the value: {2}", this.AssemblyPath, this.ResourceType, this.Thumbprint));
                            requestedProperties.Add("Thumbprint", this.Thumbprint);
                            luidValues.Add("Thumbprint", this.Thumbprint);
                        }

                        if (!string.IsNullOrEmpty(this.Name))
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a property Name with the value: {2}", this.AssemblyPath, this.ResourceType, this.Name));
                            requestedProperties.Add("Name", this.Name);
                            luidValues.Add("Name", this.Name);
                        }

                        if (!string.IsNullOrEmpty(this.Version))
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a property Version with the value: {2}", this.AssemblyPath, this.ResourceType, this.Version));
                            requestedProperties.Add("Version", this.Version);
                            luidValues.Add("Version", this.Version);
                        }

                        if (!string.IsNullOrEmpty(this.SubType))
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a property SubType with the value: {2}", this.AssemblyPath, this.ResourceType, this.SubType));
                            requestedProperties.Add("SubType", this.SubType);
                            luidValues.Add("SubType", this.SubType);
                        }

                        if (!string.IsNullOrEmpty(this.SourceDocLibUrl))
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a property SourceDocLibUrl with the value: {2}", this.AssemblyPath, this.ResourceType, this.SourceDocLibUrl));
                            requestedProperties.Add("SourceDocLibUrl", this.SourceDocLibUrl);
                            luidValues.Add("SourceDocLibUrl", this.SourceDocLibUrl);
                        }

                        switch (resourceType)
                        {
                            case "System.BizTalk:Assembly":
                            case "System.BizTalk:Bam":
                            case "System.BizTalk:BizTalkAssembly":
                            case "System.BizTalk:BizTalkBinding":
                            case "System.BizTalk:Com":
                            case "System.BizTalk:File":
                            case "System.BizTalk:PostProcessingScript":
                            case "System.BizTalk:PreProcessingScript":
                            case "System.BizTalk:WebDirectory":
                                app.ResourceCollection.Add(resourceType, this.AssemblyPath, this.Destination, requestedProperties, this.Overwrite);    
                                break;
                            case "System.BizTalk:Bas":
                            case "System.BizTalk:Certificate":
                            case "System.BizTalk:Rules":
                                app.ResourceCollection.Add(resourceType, luidValues, this.AssemblyPath, this.Destination, requestedProperties, this.Overwrite);
                                break;
                            default:
                                throw new Exception("Invalid ResourceType");
                        }
                        Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Adding resource: {0} ({1}) to Application: {2}", this.AssemblyPath, this.ResourceType, this.Application));
                    }
                    else
                    {
                        Log.LogError(string.Format(CultureInfo.InvariantCulture, "Application not found: {0}", this.Application));
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Log.LogError(string.Format(CultureInfo.InvariantCulture, "Deploy Assembly failure: {0}", ex));
                    group.Abort();
                    throw;
                }
            }
        }

        #region Private Methods

        private void AddProperties(Dictionary<string, object> requestedProperties, string propertie)
        {
            // Are there any properties
            if (!string.IsNullOrEmpty(propertie))
            {
                // First seperate multiple properties
                string[] seperatedProperties = propertie.Split(new char[] { ',' });

                foreach (string singlePropertie in seperatedProperties)
                {
                    // Now split the key with the value
                    string[] keyvaluepair = singlePropertie.Split(new char[] { '=' });

                    string key = keyvaluepair.Length > 0 ? keyvaluepair[0].Trim() : null;
                    string value = keyvaluepair.Length > 1 ? keyvaluepair[1].Trim() : null;

                    if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                    {
                        if (!requestedProperties.ContainsKey(key))
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a property {2} with the value: {3}", this.AssemblyPath, this.ResourceType, key, value));
                            // Add the propertie to the requested list
                            requestedProperties.Add(key, value);
                        }
                        else
                        {
                            Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) changed a property {2} with the value: {3}", this.AssemblyPath, this.ResourceType, key, value));
                            // Overwrite value
                            requestedProperties[key] = value;
                        }
                    }
                }
            }
        }

        private void AddOptions(Dictionary<string, object> requestedProperties, string options)
        {
            // Are there any options?
            if (!string.IsNullOrEmpty(options))
            {
                // Seperated all options
                string[] seperatedOptions = options.Split(new char[] { ',' });

                foreach (string singleOption in seperatedOptions)
                {
                    string key = singleOption.Trim();

                    if (!requestedProperties.ContainsKey(key))
                    {
                        Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) added a option {2} with the value: True", this.AssemblyPath, this.ResourceType, key));
                        // Add the options key
                        requestedProperties.Add(key, true);
                    }
                    else 
                    {
                        Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Resource {0} ({1}) changed a option {2} with the value: True", this.AssemblyPath, this.ResourceType, key));
                        // Overwrite the existing key.
                        requestedProperties[key] = true;
                    }
                }
            }
        }

        #endregion
        #endregion
    }
}

